/*
 * Copyright 2021 Scorpiour
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

package cc.bestroute.halloween;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

public class Executor implements Runnable {

    private final List<BlockingQueue<Function<Void, Void>>> QUEUE_LIST;
    private final Integer MAX_DEPTH;
    private final Void HOLDER = null;

    private boolean terminating = false;
    
    /**
     * @param queueList list of blocking queues
     * @param maxDepth max processing depth, if greater than queueList then  
     */
    public Executor(List<BlockingQueue<Function<Void, Void>>> queueList, int maxDepth) {
        if (maxDepth < 1) {
            throw new IllegalArgumentException("Max depth invalid: Should be greater than 1");
        }
        this.QUEUE_LIST = queueList;
        this.MAX_DEPTH =  maxDepth < queueList.size() ? maxDepth : queueList.size();
    }

    @Override
    public void run() {
        System.out.println("Thread " + Thread.currentThread().getId() + " start executor with max depth of priority " + Priority.fromValue(this.MAX_DEPTH - 1));
        while(true) {
            int sum = 0;
            boolean next = false;
            for (int i = 0; i < this.MAX_DEPTH; i++) {
                if (this.QUEUE_LIST.get(i).size() == 0 ) {
                    continue;
                }
                sum += this.QUEUE_LIST.get(i).size();
                try {
                    Function<Void, Void> functor = QUEUE_LIST.get(i).poll(1, TimeUnit.SECONDS);
                    if (null != functor) {
                        System.out.println("Thread " + Thread.currentThread().getId() + " poll assignment from " + Priority.fromValue(i) + " success! going to execute");
                        functor.apply(HOLDER);
                    } else {
                        System.out.println("Thread " + Thread.currentThread().getId() + " pool assignment failed");
                    }
                } catch (InterruptedException exc) {

                }
                next = true;
            }
            if (next) {
                continue;
            }
            try {
                if (terminating && sum == 0) {
                    break;
                }
                synchronized(this) {
                    // Sleep up to 10s
                        this.wait(10000);
                    }

            } catch (InterruptedException exc) {

            }
        }
        System.out.println("Thread " + Thread.currentThread().getId() + " has terminated");
    }

    public void stop() {
        synchronized(this) {
            this.terminating = true;
        }
    }
    
}
